from django.core.files.uploadedfile import InMemoryUploadedFile
from ProjectTool.common_tool.date_encoder import DateEncoder
from io import BytesIO
import json


# 将数据转换成文件流对象存进数据库的
class FileUploaded:
    def __init__(self, file, name, field_name=None, content_type='text/plain', charset=None, content_type_extra=None):
        self.file = file
        self.field_name = field_name
        self.name = name
        self.content_type = content_type
        self.charset = charset
        self.content_type_extra = content_type_extra

    def get_uploaded_file(self):
        if isinstance(self.file,str):
            obj = self.file
        else:
            obj = json.dumps(self.file,ensure_ascii=False, cls=DateEncoder)
        self.file = bytes(obj, encoding='utf-8')
        f = BytesIO()
        f.write(self.file)
        return InMemoryUploadedFile(
            f,
            self.field_name,
            self.name,
            self.content_type,
            len(self.file),
            self.charset,
            self.content_type_extra
        )
